// import { getUserInfo as getUserInfoApi } from '@/api/user'
import { defineStore } from 'pinia'
import { ref, type Ref } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'

const keepAcitve = ref({} as RouteLocationNormalized)

const keepIncludes = ref([] as RouteLocationNormalized[])

const keepIncludeNames = ref([] as string[])

const keepAcitveIndex = ref(0)

/**
 * 添加一个界面缓存
 * @param name 
 */
function addKeep(route: RouteLocationNormalized) {
    const index = keepIncludes.value.map(item => item.name).indexOf(route.name)
    if (index === -1) {
        keepIncludes.value.push(route)
        keepIncludeNames.value.push(route.meta.componentName as string)
        keepAcitve.value = route
        keepAcitveIndex.value = keepIncludes.value.length - 1
    } else {
        keepAcitve.value = keepIncludes.value[index]
        keepAcitveIndex.value = index
    }
}

/**
 * 去掉一个界面缓存
 * @param name 
 */
function subKeep(route: RouteLocationNormalized) {
    const index = keepIncludes.value.indexOf(route)
    const nameIndex = keepIncludeNames.value.indexOf(route.meta.componentName as string)
    keepIncludes.value.splice(index, 1)
    keepIncludeNames.value.splice(nameIndex, 1)
}

export default defineStore(
    'keepAlive',
    () => ({
        keepIncludes,
        keepIncludeNames,
        keepAcitve,
        keepAcitveIndex,
        addKeep,
        subKeep
    } as {
        keepIncludes: Ref<RouteLocationNormalized[]>
        keepIncludeNames: Ref<string[]>
        keepAcitveIndex: Ref<number>
        keepAcitve: Ref<RouteLocationNormalized>
        addKeep: (route: RouteLocationNormalized) => void
        subKeep: (route: RouteLocationNormalized) => void
    })
)
